import axios from "axios";
import { getUri } from "../utils";
import {
  EventStreamContentType,
  fetchEventSource,
} from "@microsoft/fetch-event-source";

const API_BASE_URL = "http://localhost:8123/api";

const request = axios.create({
  baseURL: API_BASE_URL,
  timeout: 5000,
});

export const chatSimpleChat = (message: string, chatId?: string) => {
  return request.get(
    getUri("/helloword/simple/chat", {
      query: message,
      "chat-id": chatId,
    })
  );
};

export const chatStreamChat = (
  message: string,
  chatId?: string,
  onMessage?: (message: string) => void
) => {
  const ctrl = new AbortController();
  fetchEventSource(
    getUri(API_BASE_URL + "/helloword/stream/chat", {
      query: message,
      platform: "ollama",
      // model: "deepseek-r1",
      // model: "qwen-plus",
      "chat-id": chatId,
    }),
    {
      method: "GET",
      openWhenHidden: true,
      onmessage(event) {
        if (event.event === "FatalError") {
          throw new Error(event.data);
        }
        onMessage?.(event.data);
      },
      onerror(event) {
        console.log("onerror", event);
      },
      signal: ctrl.signal,
    }
  );
};

export const chatReport = (chatId?: string) => {
  return request.get(
    getUri("/helloword/chat/report", {
      "chat-id": chatId,
    })
  );
};
